<template>
  <!-- 面包屑导航 -->
    <div style="margin-top: 20px; margin-left: 20px">
        <el-breadcrumb separator="/">
            <el-breadcrumb-item><b>我的课堂</b></el-breadcrumb-item>
            <el-breadcrumb-item @click="router.push('/classStart/studentsCourseInformation')">课程信息</el-breadcrumb-item>
            <el-breadcrumb-item @click="router.push('/classStart/teacherPostSign')">签到页面</el-breadcrumb-item>
        </el-breadcrumb>
    </div>
  <!-- 签到表格 -->
    <div class="table-container">
        <el-table :data="tableData" stripe style="width: 72%">
            <el-table-column prop="teacherName" label="任课老师" width="250px"/>
            <el-table-column prop="postTime" label="发布时间" width="250px"/>
            <el-table-column prop="actualTime" label="签到时间" width="250px"/>
            <el-table-column label="状态" width="180px">
                <template #default="scope">
                    <el-button
                            :type="getButtonType(scope.row)"
                            :disabled="scope.row.signState === 1 || scope.row.signState === 3"
                            @click="handleSignIn(scope.row)"
                    >
                        {{ getButtonText(scope.row) }}
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
  <!-- 分页按钮 -->
    <div class="demo-pagination-block">
        <el-pagination
                v-model:current-page="pagination.currentPage"
                v-model:page-size="pagination.pageSize"
                :page-sizes="[5, 10, 15, 20]"
                :total="pagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
        />
    </div>
  <!-- 签到按钮对话框 -->
    <el-dialog v-model="tableEditVisible" title="验证码" width="500px">
        <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
            <el-form-item label="验证码" prop="code">
                <el-input
                        v-model="form.code"
                        style="width: 240px"
                        placeholder="请输入验证码"
                />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="reset">取消</el-button>
                <el-button type="primary" @click="submitForm">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import request8090 from "../../../../utils/request8090.js";
import router from "../../../../router/index.js";

const tableData = ref([]);

const formRef = ref(null); // 引用表单
// 初始化的默认分页大小
const pagination = ref({
    currentPage: 1,
    pageSize: 10,
    total: 0
});
const tableEditVisible = ref(false);
const form = ref({
    code: '',
});
onMounted(() => {
    fetchSign();
});

// 获取签到信息
const fetchSign = () => {
    request8090({
        url: '/student/getsigninfo',
        method: 'GET',
        params: { currentPage: pagination.value.currentPage, size: pagination.value.pageSize, courseNumber: sessionStorage.getItem("courseNumber"), sNumber: sessionStorage.getItem("snumber") },
    })
        .then(res => {
            if (res.data.errorCode === 200) {
                tableData.value = res.data.data.records;
                pagination.value.total = res.data.data.total;
                // 在获取信息时检查是否超时
                checkTimeout();
            } else {
                ElMessage.error('获取数据失败');
            }
        })
        .catch(error => {
            console.error('请求失败:', error);
            ElMessage.error('请求失败');
        });
};

// 按钮的字体显示
const getButtonText = (row) => {
    if (row.signState === 1) {
        return '已签到';
    } else if (isTimeout(row)) {
        return '已超时';
    } else {
        return '签到';
    }
};

// 改变按钮状态
const getButtonType = (row) => {
    if (row.signState === 1) {
        return 'success';
    } else if (isTimeout(row)) {
        return 'danger';
    } else {
        return 'primary';
    }
};

// 超时则改变数据的状态
const checkTimeout = () => {
    tableData.value.forEach(row => {
        if (isTimeout(row) && row.signState === 0) {
            request8090({
                url: '/student/unsign',
                method: 'put',
                data: { id: row.id },
            })
                .then(res => {
                    if (res.data.errorCode !== 200) {
                        ElMessage.error('更新超时状态失败');
                    }
                })
                .catch(error => {
                    console.error('更新超时状态请求失败:', error);
                    ElMessage.error('更新超时状态请求失败');
                });
        }
    });
};

// 判断是否超时
const isTimeout = (row) => {
    const currentTime = new Date();
    const postTime = new Date(row.postTime);
    // 设定超时时间为发布签到时间后的10分钟
    const timeoutDuration = 10 * 60 * 1000;
    return (currentTime - postTime) > timeoutDuration;
};

// 签到按钮点击事件
const handleSignIn = (row) => {
    form.value.id = row.id;
    tableEditVisible.value = true;
    form.value.code = '';
};

// 提交签到表单
const submitForm = () => {
    formRef.value.validate((valid) => {
        if (valid) {
            request8090({
                url: '/student/sign',
                method: 'put',
                data: { id: form.value.id, snumber: sessionStorage.getItem('snumber'), code: form.value.code },
            })
                .then(res => {
                    if (res.data.errorCode === 200) {
                        ElMessage.success('签到成功');
                        fetchSign();
                        tableEditVisible.value = false;
                    } else {
                        ElMessage.error('验证码错误，签到失败');
                    }
                })
                .catch(error => {
                    console.error('签到请求失败:', error);
                    ElMessage.error('签到请求失败');
                });
        } else {
            ElMessage.error('表单验证失败，请检查输入');
        }
    });
};
const handleSizeChange = (size) => {
    pagination.value.pageSize = size;
    fetchSign();
};

const handleCurrentChange = (page) => {
    pagination.value.currentPage = page;
    fetchSign();
};
// 对话框取消按钮
const reset = () => {
    form.value.code = '';
    tableEditVisible.value = false;
};

// 校验规则
const rules = {
    code: [
        { required: true, message: '请输入验证码', trigger: 'change' },
        { pattern: /^[a-zA-Z0-9]{4}$/, message: '验证码必须是4位英文和数字', trigger: 'change' }
    ],
};

</script>

<style>
.table-container {
    margin-top: 20px;
}

.demo-pagination-block {
    margin-top: 20px;
    text-align: center;
}
</style>
